/*
 * @Description: 批量导入模板配置
 * @Author: Rfan
 * @Date: 2022-09-22 16:32:24
 * @LastEditTime: 2023-01-10 18:54:02
 */

import { useEffect, useRef, useState } from 'react';
import { Button, Form, Modal, Tabs } from 'antd';
import { fetchLevelByATId } from '@/api/archivesType';
import { fetchMetadata } from '@/api/metadata';
import { delItemById } from '@/utils/list';
import { QUERY_METADATA_ALL } from '@/view/system/Metadata/constants';
import type { FC } from 'react';
import type { ICommonDialog } from '@/interfaces/global';
import { useTemplateManageContext } from '../../contexts/TemplateManageContext';
import ExcelPane from './components/ExcelPane';
import ExcelLevel from './components/ExcelLevel';

const { TabPane } = Tabs;

interface CreateTemplateDialogProps extends ICommonDialog {
  data?: any; // 模板数据
  methodType?: any;
}

/**
 * @description: 模板配置弹窗
 * @param {CreateTemplateDialogProps} props 弹窗传入参数
 * @return {ReactDOM} 模板配置弹窗tsx
 */
const CreateTemplateDialog: FC<CreateTemplateDialogProps> = (props) => {
  const { visible, data, onClose } = props;
  const { selectAT, methodType, typeFilter, tplType } = useTemplateManageContext();
  // excel映射面板表单
  const [baseForm] = Form.useForm();
  const levelRef = useRef<any>();

  // 模板数据
  const [template, setTemplate] = useState<any>({});
  // 层级列表（不含组件级）
  const [levelList, setLevelList] = useState([]);
  // 所有层级的元数据
  const [levelMetadata, setLevelMetadata] = useState<any>({});
  // 当前选中的tab
  const [currentTab, setCurrentTab] = useState('1');

  /* 设置显示层级 */
  useEffect(() => {
    if (visible) {
      setCurrentTab('1');
      console.log('CreateTemplateDialog', data, methodType);
      fetchLevelByATId(selectAT.id).then((res) => {
        const _list = delItemById(0, res.data, 'level');
        setLevelList(_list);
        _list.forEach((item: any) => {
          const { level } = item;
          const fieldQuery = {
            metadataFieldType: QUERY_METADATA_ALL,
            coordinate: {
              atType: selectAT.atType,
              atCode: selectAT.atCode,
              level
            }
          };
          !levelMetadata[level] &&
            fetchMetadata(fieldQuery).then((res: any) => {
              setLevelMetadata((state: any) => ({
                ...state,
                [level]: res.data
              }));
            });
        });
      });
    }
  }, [visible]);

  useEffect(() => {
    if (data) {
      setTemplate(data);
    }
  }, [data]);

  const onCancel = () => {
    onClose();
  };

  const tabsChange = (key: string) => {
    setCurrentTab(key);
  };

  const saveExcelTemplate = () => {
    if (parseInt(currentTab, 10) === 1) {
      saveExcel();
    } else {
      saveRelation();
    }
  };

  const saveTemplate = () => {
    saveExcel();
  };

  const saveExcel = () => {
    baseForm.submit();
  };

  const saveRelation = () => {
    levelRef.current.submit();
  };

  return (
    <Modal
      title={`${typeFilter(tplType)}设计`}
      visible={visible}
      className="upload-template"
      width={650}
      maskClosable={false}
      destroyOnClose
      onCancel={onCancel}
      footer={[
        <Button key="close" onClick={onCancel}>
          关闭
        </Button>,
        methodType === 1 && (
          <Button
            key="next"
            onClick={() => {
              saveExcelTemplate();
            }}
          >
            {parseInt(currentTab, 10) === 1 ? '下一步' : '保存'}
          </Button>
        ),
        methodType !== 1 && (
          <Button
            key="save"
            onClick={() => {
              saveTemplate();
            }}
          >
            保存
          </Button>
        )
      ]}
    >
      {methodType === 1 ? (
        <Tabs activeKey={currentTab} onChange={tabsChange}>
          <TabPane tab="EXCEl表创建" key={1}>
            <ExcelPane
              levelList={levelList}
              levelMetadata={levelMetadata}
              form={baseForm}
              tplData={data}
              setIndexTab={setCurrentTab}
              updateTemplate={setTemplate}
            />
          </TabPane>
          <TabPane tab="EXCEL层级间匹配关系" key={2}>
            <ExcelLevel
              ref={levelRef}
              levelList={levelList}
              levelMetadata={levelMetadata}
              tplData={template}
              templateId={template.id}
              closeDialog={onCancel}
            />
          </TabPane>
        </Tabs>
      ) : (
        <ExcelPane
          levelList={levelList}
          levelMetadata={levelMetadata}
          form={baseForm}
          tplData={data}
          setIndexTab={setCurrentTab}
          updateTemplate={setTemplate}
          closeDialog={onClose}
        />
      )}
    </Modal>
  );
};

export default CreateTemplateDialog;
